

import { View } from "@tarojs/components";
import Taro from '@tarojs/taro';
import React from "react";
import { useWindowSize } from 'react-use';
import type { FitScreenProps, FitSize } from '../../types/FitScreen';



export const useFitSize:
    () => FitSize
    = () => {
        const { width, height } = useWindowSize();
        const getDeviceInfo = React.useMemo(() => Taro.getDeviceInfo(), [])
        type ReducerProp = (state: FitSize, action: Partial<FitSize>) => FitSize
        const [state, dispatch] = React.useReducer<ReducerProp>(
            (state, action) => ({ ...state, ...action }),
            {
                _width: 0,
                _height: 0
            })

        React.useEffect(() => {
            if (getDeviceInfo.brand.indexOf('Phone') >= 0) {
                dispatch({
                    _width: width,
                    _height: height
                })
            } else {
                if (width >= height * 0.8) {
                    dispatch({
                        _width: height * 0.56,
                        _height: height
                    })
                } else {
                    dispatch({
                        _width: width,
                        _height: height
                    })
                }
            }

        }, [width])


        // console.log({
        //     width,
        //     height,
        //     getDeviceInfo
        // })

        return state
    }









export const FitScreen:
    React.FC<FitScreenProps>

    = props => {

        const { _width, _height } = useFitSize();
        // console.log({ _width, _height ,'getSystemInfoSync':Taro.getSystemInfoSync(),'getWindowInfo':Taro.getWindowInfo()})

        let height: string = (props.style as any)?.height

        const getDeviceInfo = React.useMemo(() => Taro.getDeviceInfo(), [])
        if (getDeviceInfo.brand.indexOf('Phone') >= 0) {
            return React.createElement(View, { style: { width: '100vw', height: '100vh' } }, props.children)
        }
        return React.createElement(View,
            {
                style: {
                    ...styles.container,
                    ...props.style as object,
                    width: `${_width}px`,
                    height: height ? height : `${_height}px`,
                }
            },
            props.children
        )
    }



const styles: Record<string, React.CSSProperties> = {
    container: {
        display: 'flex',
        flexDirection: 'column',
        width: '100%',
        height: 'calc(100%)',
        // backgroundColor: 'white',
        position: 'relative',
        flexGrow: 0,
        flexShrink: 0,
    },

}


